<?php
// $Id$
$config_dir =  dirname(dirname(dirname(__FILE__))) . "/config/";
require_once( $config_dir . "config.controller.inc.php");
/**
 * Controller_Category 控制器
 */
class Controller_Category extends Controller_Abstract
{

	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
    
	function actionGenerateCategoryTree()
	{
        try
        {
            $category_tree  = $this->getCategoryTree("root_category");
            $json = "fillAct(" . json_encode($category_tree) . ", \"public\/category_tree\");";
            $fh = fopen(JSON_CATEGORY_TREE_PATH, "w");
            if ( $fh == null )
            {
                //echo $callback .  "(" . $json . ")";
                exit();
            }
            fwrite($fh, $json);
            fclose($fh);
        }
        catch (Exception $ex)
        {
            print_r($ex);
            exit();
        }
	}
    
	function actionNewCategory()
	{
        $form = new Form_NewCategory(url('category/newcategory'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                $category = new GoodsCategory($form->values());
                $values = $form->values();
                $category->category_id = $values["category_id"];
                $category_querry = GoodsCategory::find("category_id = ?", $category->category_id)->getOne();
                if ( $category_querry != null && $category_querry->category_id != null )
                {
                    $ret = array();
                    $ret["answer"] = "new_category";
                    $ret["ret_code"] = -1;
                    $ret["info"] = "New category failed, category exist.";
                    $ret["data"] = "";
                    $callback = $values["callback"];
                    echo $callback .  "(" . json_encode($ret) . ")";
                    exit();
                }
                else
                {
                    $category->category_name = $values["category_name"];
                    $category->super_category_id = $values["super_category_id"];
                    $category->keywords = $values["keywords"];
                    $category->description = $values["description"];
                    $category->url = $values["url"];
                    $category->recommend_json_url = $values["recommend_json_url"];
                    $category->normal_json_url = $values["normal_json_url"];
                    $category->html_template_path = $values["html_template_path"];
                    $category->save(99,'create');
                    
                    $ret = array();
                    $ret["answer"] = "new_category";
                    $ret["ret_code"] = 1;
                    $ret["info"] = "";
                    $ret["data"] = "";
                    $callback = $values["callback"];
                    echo $callback .  "(" . json_encode($ret) . ")";
                    exit();
                }
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
	}
    
    function getCategoryTree($category_id)
    {
        if ( $category_id == null )
        {
            return null;
        }
        try
        {
            $category_tree = Array();
            $child_category = GoodsCategory::find("super_category_id = ?", $category_id)->getAll();
            while ( $child_category->current() )
            {
                $category_current = $child_category->current();
                $category_item["category_id"] = $category_current->category_id;
                $category_item["super_category_id"] = $category_current->super_category_id;
                $category_item["category_name"] = $category_current->category_name;
                $category_item["keywords"] = $category_current->keywords;
                $category_item["child_category_ids"] = $category_current->child_category_ids;
                $category_item["create_time"] = $category_current->create_time;
                $category_item["update_time"] = $category_current->update_time;
                $category_item["url"] = $category_current->url;
                $category_item["recommend_json_url"] = $category_current->recommend_json_url;
                $category_item["normal_json_url"] = $category_current->normal_json_url;
                $category_item["html_template_path"] = $category_current->html_template_path;
                $category_item["comment"] = $category_current->comment;
                $category_item["ext0"] = $category_current->ext0;
                $category_item["ext1"] = $category_current->ext1;
                $category_item["ext2"] = $category_current->ext2;
                
                $category_tree_index = count($category_tree);
                $category_tree[$category_tree_index]["self"] = $category_item;
                $category_tree[$category_tree_index]["child"] = $this->getCategoryTree($category_item["category_id"]);
                $child_category->next();
            }
            return $category_tree;
        }
        catch (Exception $ex)
        {
            print_r($ex);
            exit();
        }
    }
    
    function actionGenerateCategoryGoodsJSON()
    {
        $form = new Form_GenerateCategoryGoodsJSON(url('category/generatecategorygoodsjson'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                $values = $form->values();
                
                $goods_category_item = GoodsCategory::find("category_id = ?", $values["category_id"])->getOne();
                $goods_category = Array();
                $goods_category["category_name"] = $goods_category_item->category_name;
                $goods_category["category_id"] = $values["category_id"];
                
                $category_goods = Array();
                $goods_index = 0;
                $goods_info_list = GoodsInfo::find("category_id = ?", $values["category_id"])->getAll();
                
                while ( $goods_info_list->current() )
                {
                    $goods_info_item = $goods_info_list->current();
                    $goods_property = GoodsProperty::find("property_id = ?",$goods_info_item->property_id)->getOne();
                    $goods_onshelf_list = GoodsOnshelf::find("goods_id = ?",$goods_info_item->goods_id)->getAll();
                    
                    while ( $goods_onshelf_list->current() )
                    {
                        $goods_onshelf_item = $goods_onshelf_list->current();

                        $category_goods[$goods_index]["goods_id"] = $goods_info_item->goods_id;
                        $category_goods[$goods_index]["goods_name"] = $goods_info_item->goods_name;
                        //$category_goods[$goods_index]["goods_no"] = $goods_info_item->goods_no;
                        $category_goods[$goods_index]["small_img_urls"] = $goods_info_item->small_img_urls;
                        $category_goods[$goods_index]["img_urls"] = $goods_info_item->img_urls;
                        $category_goods[$goods_index]["big_img_urls"] = $goods_info_item->big_img_urls;
                        
                        $category_goods[$goods_index]["goods_onshelf_id"] = $goods_onshelf_item->goods_onshelf_id;
                        $category_goods[$goods_index]["stock"] = $goods_onshelf_item->stock;
                        $category_goods[$goods_index]["market_price"] = $goods_onshelf_item->market_price;
                        $category_goods[$goods_index]["mall_price"] = $goods_onshelf_item->mall_price;
                        $category_goods[$goods_index]["vip_price"] = $goods_onshelf_item->vip_price;
                        
                        ++$goods_index;
                        $goods_onshelf_list->next();
                    }
                    $goods_info_list->next();
                }
                
                $category_json = Array();
                $category_json["category"] = $goods_category;
                $category_json["goods"] = $category_goods;
                
                $json_path = JSON_CATEGORY_GOODS_PATH . $goods_category_item->super_category_id . "/";
                if ($json_path != '.' && $json_path != '..' && !is_dir($json_path))
                {
                    passthru("mkdir -p $json_path >/dev/null");
                }
                
                $json_name = $json_path. $goods_category_item->category_id . ".js";
                $json = "fillAct(" . json_encode($category_json) . ", 'category/category_goods');";
                $fh = fopen($json_name, "w");
                if ( $fh == null )
                {
                    //echo $callback .  "(" . $json . ")";
                    exit();
                }
                fwrite($fh, $json);
                fclose($fh);
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
    
    function actionGenerateCategoryGoodsRecommendedJSON()
    {
        $form = new Form_GenerateCategoryGoodsJSON(url('category/generatecategorygoodsjson'));
        if ( $this->_context->isPOST() && $form->validate($_POST) )
        {
            try
            {
                if ( $_FILES["goods_file_xls"]["error"] > 0 )
                {
                    echo "error: " . $_FILES["goods_file_xls"]["error"] . "<br />";
                    exit();
                }
                else if ($_FILES["goods_file_xls"]["type"] != "application/vnd.ms-excel")
                {
                    echo $_FILES["goods_file_xls"]["name"] . "is not a excel file.<br />";
                    exit();
                }
                else
                {
                    $time_now = gettimeofday();
                    $time_now_version = $time_now["sec"] . $time_now["usec"];
                    $xls_file = XLS_UPLOAD_GOODS_PATH . $time_now["sec"] . $time_now["usec"] . $_FILES["goods_file_xls"]["name"];
                    if (file_exists($xls_file))
                    {
                        echo $_FILES["goods_file_xls"]["name"] . " already exists. ";
                        exit();
                    }
                    else
                    {
                        move_uploaded_file($_FILES["goods_file_xls"]["tmp_name"], $xls_file);
                        $xls_data = new Spreadsheet_Excel_Reader();
                        $xls_data->setOutputEncoding("UTF-8");
                        $xls_data->read($xls_file);
                        $json_goods = new Array();
                        for ($i = 2; $i <= $xls_data->sheets[0]['numRows']; $i++)
                        {
                            $goods_onshelf_id = $xls_data->sheets[0]['cells'][$i][1];
                            $goods_onshelf = GoodsOnshelf::find("goods_onshelf_id = ?", $goods_onshelf_id)->getOne();
                            if (!$goods_onshelf->goods_id)
                            {
                                exit();
                            }
                            $goods_info = GoodsInfo::find("goods_id = ?", $goods_onshelf->goods_id)->getOne();
                            if (!$goods_info->property_id)
                            {
                                exit();
                            }
                            $goods_property = GoodsProperty::find("property_id = ?", $goods_info->property_id)->getOne();
                            $brand = Brand::find("brand_id = ?", $goods_info->brand_id)->getOne();
                            
                            $json_goods[$i-2]["goods_onshelf_id"] = $goods_onshelf_id;
                            $json_goods[$i-2]["goods_name"] = $goods_info->goods_name;
                            $json_goods[$i-2]["goods_no"] = $goods_info->goods_name;
                            $json_goods[$i-2]["brand_name"] = $brand->brand_name;
                            $json_goods[$i-2]["detail"] = $goods_info->detail;
                            $json_goods[$i-2]["img_urls"] = $goods_info->img_urls;
                            $json_goods[$i-2]["weight"] = $goods_onshelf_id;
                            $json_goods[$i-2]["quantity"] = $goods_onshelf_id;
                            $json_goods[$i-2]["unit"] = $goods_onshelf_id;
                            $json_goods[$i-2]["color"] = $goods_onshelf_id;
                            $json_goods[$i-2]["model"] = $goods_onshelf_id;
                            $json_goods[$i-2]["size"] = $goods_onshelf_id;
                            $json_goods[$i-2]["stock"] = $goods_onshelf_id;
                            $json_goods[$i-2]["mall_price"] = $goods_onshelf_id;
                            $json_goods[$i-2]["vip_price"] = $goods_onshelf_id;
                        }
                        $goods_category = GoodsCategory::find("category_id = ?", $goods_info->category_id)->getOne();
                        $json = new Array();
                        $json["goods_recommended"] = $json_goods;
                        $json_string = "fillAct(" . json_encode($json) . ", 'category/category_goods_recommended');";
                        $json_path = JSON_CATEGORY_RECOMMENDED_PATH . $goods_category->super_category_id . "/";
                        if ($json_path != '.' && $json_path != '..' && !is_dir($json_path))
                        {
                            passthru("mkdir -p $json_path >/dev/null");
                        }
                        
                        $json_name = $json_path. $goods_info->category_id . ".js";
                        $fh = fopen($json_name, "w");
                        if ( $fh == null )
                        {
                            //echo $callback .  "(" . $json . ")";
                            exit();
                        }
                        fwrite($fh, $json_string);
                        fclose($fh);
                    }
                }
            }
            catch (Exception $ex)
            {
                print_r($ex);
                exit();
            }
        }
    }
}


